class HTTP {
  http: XMLHttpRequest | undefined;
  constructor() {
    this.init();
  }
  init() {
    this.http = new XMLHttpRequest();
    this.http.timeout = 10000;
    this.http.onloadstart = () => {
      // 刚接收到数据
    };
    this.http.onabort = () => {
      // 请求关闭
    };
    this.http.onloadend = () => {
      // 请求结束
    };
  }
  // 上传文件
  upload(
    url: string,
    file: FormData,
    uploadCallback: (e: ProgressEvent<EventTarget>) => void,
    async: boolean = true
  ): Promise<any> {
    return new Promise((resolve, reject) => {
      if (this.http) {
        // @ts-ignore
        this.http.onload = ({ target }: { target: XMLHttpRequest }) => {
          try {
            resolve(JSON.parse(target.response));
          } catch (err) {
            reject(target.response);
          }
        }; // 请求成功
        this.http.upload.onprogress = (e: ProgressEvent<EventTarget>) => {
          uploadCallback(e);
        };
        this.http?.open("POST", url, async);
        this.http?.send(file);
      } else {
        reject("出错了");
      }
    });
  }
  // 发送请求
  setRequest(
    method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH",
    url: string,
    body?: { [key: string]: any },
    header?: { [key: string]: string },
    async: boolean = true
  ): Promise<any> {
    return new Promise((resolve, reject) => {
      if (this.http) {
        // @ts-ignore
        this.http.onload = ({ target }: { target: XMLHttpRequest }) => {
          try {
            resolve(JSON.parse(target.response));
          } catch (err) {
            reject(target.response);
          }
        }; // 请求成功
        this.http.ontimeout = (outime) => reject(outime); // 请求超时
        this.http.onerror = (err) => reject(err); // 请求错误
        this.http?.open(method, url, async);
        if (method === ("POST" || "PUT" || "PATCH")) {
          this.http?.setRequestHeader(
            // 设置setRequestHeader必须在open后send前
            "Content-Type",
            "application/x-www-form-urlencoded"
          );
        }
        if (header)
          // 设置请求头
          Object.keys(header).forEach((item) => {
            this.http?.setRequestHeader(item, header[item]);
          });
        this.http?.send(
          method === "POST" || "PUT" || "PATCH"
            ? body
              ? Object.keys(body).reduce(
                  (total, item) => `${total}${item}=${body[item]}&`,
                  ""
                )
              : ""
            : JSON.stringify(body)
        );
      } else {
        reject("http出错");
      }
    });
  }
  about() {
    // 取消请求
    this.http?.abort();
  }
}

// if (!window?.http) window.http = new HTTP();

// let http: HTTP = window?.http ? window?.http : new HTTP();

let http = new HTTP()

export { http, HTTP };
